<script setup lang="ts">
import { getMessageList, getSession, readMessage } from '@/api/message';
import { Message, MessageList, Session } from '@/api/message/type';
import Header from './components/Header.vue';
import Bottom from './components/Bottom.vue';
import { useUserStore } from '@/store/user';
import { listen } from '@tauri-apps/api/event';
import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/plugin-notification';
import { onMounted, ref, nextTick} from 'vue';
import { useRoute } from 'vue-router';

const messageList = ref({} as MessageList);
const userId = ref('');
const session = ref({} as Session)
const chatContent = ref<HTMLDivElement>() //装会话的容器

onMounted(() => {
    const userStore = useUserStore();
    userId.value = userStore.getId;
    session.value.senderId = userId.value;
    const route = useRoute();
    session.value.receiverId = route.query.receiverId as string;
    session.value.id = route.query.sessionId as string;
    if (session.value.id == undefined) {
        getSession(session.value).then((res) => {
            session.value = res.data as Session;
            refresh();
        }).catch((e) => {
            console.log('e =>', e);
        })
    }
})

const refresh = () => {
    if (session.value.id != undefined) {
        getMessageList(session.value.id)
            .then((res) => {
                const {receiver, sender, list} = res.data as MessageList;
                if (userId.value === sender.id) {
                    messageList.value.sender = sender;
                    messageList.value.receiver = receiver;
                } else {
                    messageList.value.sender = receiver;
                    messageList.value.receiver = sender;
                }
                messageList.value.list = list;
                scrollToBottom();
            })
        readMessage(session.value.id, session.value.senderId);
    }
}


listen<Message>('/chat/message', async (event) => {
    messageList.value.list.push(event.payload);
    readMessage(session.value.id, session.value.senderId);
    scrollToBottom();
    // 你有发送通知的权限吗？
    let permissionGranted = await isPermissionGranted();
    // 如果没有，我们需要请求它
    if (!permissionGranted) {
        const permission = await requestPermission();
        permissionGranted = permission === 'granted';
    }
    // 一旦获得许可，我们就可以发送通知
    if (permissionGranted) {
        sendNotification({ title: '消息', body: '你收到来自好友的一条消息！' });
    }
})

const scrollToBottom= ()=> {
    //注意要使用nexttick以免获取不到dom
    nextTick(() => {
        if (chatContent.value != undefined) {
            chatContent.value.scrollTop = chatContent.value.scrollHeight - chatContent.value.offsetHeight
        }
    })
}
</script>

<template>
    <div class="container">
        <Header></Header>
        <div class="content">
            <div class="chat-height">
                <div class="chat" ref="chatContent">
                    <div class="list">
                        <div class="item" v-for="(item, _index) in messageList.list">
                            <div class="left" v-if="userId !== item.senderId">
                                <div>
                                    <van-image :src="messageList.receiver.avatar" round width="40" height="40"/>
                                </div>
                                <div class="left-right">
                                    <div class="info">
                                        <p style="margin: 0%; font-size: 14px; margin-right: 3%; margin-left: 3%;">{{ messageList.receiver.nickname }}</p>
                                        <p style="margin: 0%; font-size: 12px;">{{ item.sendTime }}</p>
                                    </div>
                                    <div class="content-text">
                                        <p class="text">{{ item.content }}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="right" v-else-if="userId === item.senderId">
                                <div class="right-left">
                                    <div class="info">
                                        <p style="margin: 0%; font-size: 12px;">{{ item.sendTime }}</p>
                                        <p style="margin: 0%; font-size: 14px; margin-right: 3%; margin-left: 3%;">{{ messageList.sender.nickname }}</p>
                                    </div>
                                    <div class="content-text">
                                        <p class="text">{{ item.content }}</p>
                                    </div>
                                </div>
                                <div>
                                    <van-image :src="messageList.sender.avatar" round width="40" height="40"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <Bottom v-bind:session="session" v-bind:user-id="userId" v-on:send="refresh"></Bottom>
    </div>
</template>

<style lang="scss" scoped>
.text {
    padding: 4%;
    background-color: white;
    margin: 0%;
    border-radius: 15px;
}
.container {
    height: 100%;
    .content {
        height: calc(100% - 106px);
        display: flex;
        flex-direction: column;
        .chat-height {
            display: flex;
            justify-content: center;
            height: 100%;
            .chat {
                flex-direction: column;
                width: 100%;
                display: flex;
                overflow-y: scroll;
                -ms-overflow-style: none; /* 适用于 Internet Explorer 和旧版 Edge */
                scrollbar-width: none; /* 适用于 Firefox */
                .list {
                    width: 100%;
                    display: flex;
                    flex-direction: column;            
                    .item {
                        width: 100%;
                        display: flex;
                        .left {
                            display: flex;
                            flex-direction: row;
                            justify-content: left;
                            margin: 3%;
                            width: 100%;
                            .left-right {
                                width: 70%;
                                display: flex;
                                flex-direction: column;
                                justify-content: right;
                                align-items: right;
                                .info {
                                    display: flex;
                                    align-items: center;
                                }
                                .content-text {
                                    height: 100%;
                                    display: flex;
                                    justify-content: start;
                                    border-radius: 10px;
                                    margin-top: 1%;
                                    margin-left: 2%;
                                }
                            }
                        }
                        .right {
                            display: flex;
                            flex-direction: row;
                            justify-content: right;
                            margin: 3%;
                            width: 100%;
                            .right-left {
                                width: 70%;
                                display: flex;
                                flex-direction: column;
                                justify-content: right;
                                align-items: right;
                                .info {
                                    display: flex;
                                    justify-content: right;
                                    align-items: center;
                                }
                                .content-text {
                                    height: 100%;
                                    display: flex;
                                    justify-content: start;
                                    border-radius: 10px;
                                    margin-top: 1%;
                                    margin-right: 2%;
                                    justify-content: right;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>